﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;


namespace CommonInteractive.Config
{
    

    public class ResolveAssembly : IDisposable
    {


        public ResolveAssembly(bool optimist, IEnumerable<Assembly> assemblies)
        {

            _Assemblies = assemblies;
            this._optimist = optimist;
            

        }

        public void Dispose()
        {
            Stop();
        }

        /// <summary>
        /// Resolve the type not found
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public Assembly MyResolveEventHandler(object sender, ResolveEventArgs args)
        {
            string name = args.Name;
            return FindInRepository(name);
        }

        private Assembly FindInRepository(string name)
        {

            foreach (var item in _Assemblies)
                if (item.FullName == name)
                    return item;

            if (_optimist)
            {

                string nn1 = name.Split(',')[0];

                foreach (var item in _Assemblies)
                {
                    string nn2 = item.FullName.Split(',')[0];
                    if (nn1 == nn2)
                        return item;
                }
            }

            return null;
        }


        private bool IsListen = false;

        public void Stop()
        {

            if (!IsListen)
                return;

            AppDomain.CurrentDomain.AssemblyResolve -= MyResolveEventHandler;
            IsListen = false;
        }

        public void Start()
        {

            if (IsListen)
                return;

            AppDomain.CurrentDomain.AssemblyResolve += MyResolveEventHandler;
            IsListen = true;

        }



        private IEnumerable<Assembly> _Assemblies { get; set; }
        private bool _optimist { get; set; }

    }

}
